<?php   // $Id: fact_add_remove_bon.php 207 2008-06-06 12:26:53Z pcoustillas $ ?>
<?php
require_once("include/verif.php");
require_once("include/config/common.php");

$num_fact=isset($_POST['num_fact'])?$_POST['num_fact']:"";
$moins=isset($_POST['retirer'])?$_POST['retirer']:""; //contient le numero du bon
$plus=isset($_POST['ajouter'])?$_POST['ajouter']:""; //contient le numero du bon

$sql = "SELECT client FROM ${tblpref}facture WHERE num = $num_fact";
$req = mysql_query($sql) or die("Erreur SQL !<br/>$sql<br/>" . mysql_error());
$data = mysql_fetch_array($req);
//$list_num = unserialize($data['list_num']);

if ($moins !='') //retirer un bon de commande.
{
	$sql = "UPDATE ${tblpref}bon_comm SET num_facture=0 WHERE num_bon=$moins";
	mysql_query($sql) or die("Erreur SQL, retirer le bon n°$moins !<br/>$sql<br/>" . mysql_error());
}

if ($plus!='') { //ajouter un bon de commande.
	$sql = "UPDATE ${tblpref}bon_comm SET num_facture=$num_fact WHERE num_bon=$plus";
	mysql_query($sql) or die("Erreur SQL, ajouter le bon n°$plus !<br/>$sql<br/>" . mysql_error());
}

//dans tous les cas metre à jour les montants de la facture.
$sql="SELECT sum(tot_htva) as sum_tot_ht FROM ${tblpref}bon_comm WHERE num_facture=$num_fact";
$result=mysql_query($sql) or die("Erreur SQL, montant facture !<br/>$sql<br/>" . mysql_error());
$sum_tot_ht=mysql_result($result,0);
$sum_tot_ht=is_null($sum_tot_ht)?0:$sum_tot_ht; //si la requete ne retourne rien faut prendre 0


$sql="SELECT sum(tot_tva) as sum_tot_tva FROM ${tblpref}bon_comm WHERE num_facture=$num_fact";
$result=mysql_query($sql) or die("Erreur SQL, montant facture !<br/>$sql<br/>" . mysql_error());
$sum_tot_tva=mysql_result($result,0);
$sum_tot_tva=is_null($sum_tot_tva)?0:$sum_tot_tva; //si la requete ne retourne rien faut prendre 0

$sum_ttc = $sum_tot_ht + $sum_tot_tva;

$sql_maj_fact="UPDATE ${tblpref}facture SET total_fact_h=$sum_tot_ht,total_fact_ttc=$sum_ttc WHERE num=$num_fact";
mysql_query($sql_maj_fact) or die("Erreur SQL, mise à jour facture !<br/>$sql_maj_fact<br/>" . mysql_error());


header("Location: fact_edit.php?num_fact=$num_fact");

?>
